const SerialPort = require('serialport')
const { SerialPortModel } = require('../../models/models')
const crc = require('../tools/crc16')
const getEnquire = require('../tools/getEnquire')


class Serial {
    constructor(com = 'com1', baudRate = 9600) {
        this.port = new SerialPort(com, {
            baudRate
        })
        this.interVal = {}
        this.port.on('data', (data) => {
            const hexData = data.toString('hex')
            if (hexData.substr(-4) === crc(hexData.slice(0, -4))) {
                console.log(hexData)
                new SerialPortModel({
                    com,
                    slaverIndex: hexData.substr(0, 2),
                    value: hexData,
                    createTime: Date.now()
                }).save()

            }

        })
    }

    setQuerySchedul(queryList = []) {
        queryList.forEach((item, index) => {
            const { slaver, plc, time } = item;
            this.interVal[index] = setInterval(() => {
                const querywithcrc = getEnquire(slaver, plc, {
                    buff: true
                })
                this.port.write(querywithcrc)
            }, time)
        })

    }

}



const test = new Serial('com5', 9600)
test.setQuerySchedul([{ slaver: '1', plc: '40012', time: 2000 }])